package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"time"

	crono "github.com/utahta/go-cronowriter"
	"github.com/gin-gonic/gin"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	StorePath            = kingpin.Flag("path", "stores base path").Default(".").Short('s').String()
	TableDefineFile      = kingpin.Flag("table", "table define file").Short('f').String()
	IntervalToCloseStore = kingpin.Flag("interval", "interval to to CloseStore, in second").Short('i').Default("3600").Int()
	Port                 = kingpin.Flag("port", "port to listen").Default("80").Short('p').String()
	OpenDuration         = kingpin.Flag("open", "duration to keep store open, in second").Default("3600").Short('o').Int64()
	ReadDuration         = kingpin.Flag("read", "duration to keep store read, in second").Default("3600").Short('r').Int64()
	WriteDuation         = kingpin.Flag("write", "duration to keep store writen, in second").Default("3600").Short('w').Int64()
)

func main() {
	kingpin.Parse()
	controller, err := NewController(*TableDefineFile, *StorePath, *IntervalToCloseStore)
	defer controller.Close()
	if err != nil {
		os.Exit(1)
	}
	gin.DisableConsoleColor()
	logger := crono.MustNew("logs/everylog.log.%Y%m%d", crono.WithInit())
	defer logger.Close()
	gin.DefaultWriter = io.MultiWriter(logger)
	r := gin.Default()
	r.GET("everylog/:appid/:tablename", controller.getTableHandler)
	r.GET("everylog/:appid/:tablename/:Key", controller.readGetHandler)
	r.POST("everylog/:appid/:tablename", func(ctx *gin.Context) {
		if ctx.PostForm("key_prefix") != "" {
			controller.readPostHandler(ctx)
		} else if ctx.PostForm("index") != "" {
			controller.createTableHandler(ctx)
		} else if ctx.PostForm("data") != "" {
			controller.writeHandler(ctx)
		} else {
			ctx.AbortWithError(404, fmt.Errorf("request parameters error"))
		}
	})
	r.DELETE("everylog/:appid/:tablename/:key", controller.deleteHandler)
	// r.Run(":" + *Port)
	srv := &http.Server{
		Addr:         ":" + *Port,
		Handler:      r,
		ReadTimeout:  time.Second * 5,
		WriteTimeout: time.Second * 10,
	}
	srv.ListenAndServe()
}
